package com.zxmzy.scaffold.core.net.error

import com.google.gson.JsonParseException
import com.google.gson.stream.MalformedJsonException
import org.json.JSONException
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.text.ParseException
import javax.net.ssl.SSLException

/**
 * @author zhangxiaoming
 * @date 2023/7/27
 * @description
 */
object ExceptionHandler {
    @Suppress("ThrowableNotThrown")
    fun handleException(e: Throwable): ApiException {
        val ex: ApiException = when (e) {
            is ApiException -> e
            is HttpException ->
                when (e.code()) {
                    ERROR.UNAUTHORIZED.code -> ApiException(ERROR.UNAUTHORIZED, e)
                    ERROR.FORBIDDEN.code -> ApiException(ERROR.FORBIDDEN, e)
                    ERROR.NOT_FOUND.code -> ApiException(ERROR.NOT_FOUND, e)
                    ERROR.REQUEST_TIMEOUT.code -> ApiException(ERROR.REQUEST_TIMEOUT, e)
                    ERROR.GATEWAY_TIMEOUT.code -> ApiException(ERROR.GATEWAY_TIMEOUT, e)
                    ERROR.INTERNAL_SERVER_ERROR.code -> ApiException(ERROR.INTERNAL_SERVER_ERROR, e)
                    ERROR.BAD_GATEWAY.code -> ApiException(ERROR.BAD_GATEWAY, e)
                    ERROR.SERVICE_UNAVAILABLE.code -> ApiException(ERROR.SERVICE_UNAVAILABLE, e)
                    else -> ApiException(e.code(), e.message(), e)
                }

            is JsonParseException,
            is JSONException,
            is ParseException,
            is MalformedJsonException -> ApiException(ERROR.PARSE_ERROR, e)

            is ConnectException -> ApiException(ERROR.NETWORK_ERROR, e)
            is SSLException -> ApiException(ERROR.SSL_ERROR, e)
            is SocketException,
            is SocketTimeoutException -> ApiException(ERROR.TIMEOUT_ERROR, e)

            is UnknownHostException -> ApiException(ERROR.UNKNOWN_HOST)
            else -> if (!e.message.isNullOrEmpty()) ApiException(
                ERROR.UNKNOWN.code,
                e.message!!,
                e
            ) else ApiException(ERROR.UNKNOWN, e)
        }
        return ex
    }
}